package com.atguigu.fruit.servlets;

import com.atguigu.fruit.dao.FruitDAO;
import com.atguigu.fruit.dao.impl.FruitDAOImpl;
import com.atguigu.fruit.pojo.Fruit;
import com.atguigu.myssm.myspringmvc.ViewBaseServlet;
import com.atguigu.myssm.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/add.do")
public class AddServlet extends ViewBaseServlet {

    private FruitDAO fruitDAO = new FruitDAOImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String fname = req.getParameter("fname");
        String rprice = req.getParameter("price");
        String rcount = req.getParameter("fcount");
        String remark = req.getParameter("remark");

        //这几个字段不能为空
        if (StringUtil.isEmpty(fname)||StringUtil.isEmpty(rprice)||StringUtil.isEmpty(rcount)) {
            req.setAttribute("msg","水果的名称，价格，数量不能为空！");
            processTemplate("error",req,resp);
        }else {
            int price = Integer.parseInt(rprice);
            int fcount = Integer.parseInt(rcount);
            Fruit fruit = new Fruit();
            fruit.setFname(fname);
            fruit.setFcount(fcount);
            fruit.setPrice(price);
            fruit.setRemark(remark);
            //仍然是没有处理异常的，知道正式项目要处理即可
            fruitDAO.addFruit(fruit);
            resp.sendRedirect("index");
        }
    }
}
